package com.ruoyi.framework.satoken.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.ruoyi.framework.satoken.LoginUser;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.service.ISysMenuService;
import com.ruoyi.project.system.service.ISysRoleService;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;

/**
 * 自定义权限加载接口实现类
 */
@Component // 保证此类被 SpringBoot 扫描，完成 Sa-Token 的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

	@Autowired
	private ISysRoleService roleService;

	@Autowired
	private ISysMenuService menuService;

	/**
	 * 返回一个账号所拥有的权限码集合
	 */
	@Override
	public List<String> getPermissionList(Object loginId, String loginType) {

		LoginUser loginUser = (LoginUser) StpUtil.getSession().get("loginUser");
		 Set<String> perms = new HashSet<String>();
		if (loginUser.getUser().isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = loginUser.getUser().getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(loginUser.getUserId()));
            }
        }
		return new ArrayList<>(perms);
	}

	/**
	 * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
	 */
	@Override
	public List<String> getRoleList(Object loginId, String loginType) {
		LoginUser loginUser = (LoginUser) StpUtil.getSession().get("loginUser");
		Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (loginUser.getUser().isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(loginUser.getUserId()));
        }
		return new ArrayList<>(roles);
	}

}
